package com.ship.common.core.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ObjectUtils {


    /**
     * 对象转map
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToHashMap(Object obj) throws IllegalAccessException {
        Map<String, Object> hashMap = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            hashMap.put(field.getName(), field.get(obj));
        }
        return hashMap;
    }

    /**
     * map转对象
     * @param hashMap
     * @param clazz
     * @param <T>
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> T hashMapToObject(Map<String,Object> hashMap, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        T obj = clazz.newInstance();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (hashMap.containsKey(fieldName)) {
                field.set(obj, hashMap.get(fieldName));
            }
        }
        return obj;
    }
}
